package com.RHECmap.com;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;


import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;


public class selfMap extends MapActivity {

	private MapView mapView;
	private MapController map_controller;	
	private List<Overlay> OverlayList;	
	private SelfItemizedOverlay selfitemizedoverlay;	
	private MyLocationOverlay myLocationOverlay;
	private List<GeoPoint> gp ;
	private boolean showpathState = false;
	private boolean animatelocationState = false;
	private boolean only_path_state = false;
	private RouteOverlay r;
	private int  gp_size = 1;
	private Thread myThread = null;
	private Thread myThread2 = null;
	public TextView destence_of_path;
	private Runnable runnable;
	private boolean kill_run = false;
	
	@Override
	protected void onCreate(Bundle arg0) {		
		super.onCreate(arg0);
		setContentView(R.layout.showselfmap);
		destence_of_path = (TextView) findViewById(R.id.textView1);
		mapView = (MapView)findViewById(R.id.map_view);	   		
	    mapView.setBuiltInZoomControls(true);	
	    map_controller = mapView.getController();	   
	    map_controller.setZoom(14); 	    
		 
	    set_location();
	    
		
	}

	@Override
	protected boolean isRouteDisplayed() {		
		return false;
	}

	@Override
	public void onBackPressed() {		
		super.onBackPressed();
		finish();
	}
	
	private void draw_path()
	{
		for(int i = 1; i<gp.size(); i++ ){
				GeoPoint point;
		      	point = gp.get(i);	
		      	Data.pat_length += get_destence(gp.get(i-1), gp.get(i))/1000;
		        r = new RouteOverlay(gp.get(i-1), gp.get(i), Color.RED);
		        OverlayList.add(r); 	
		        map_controller.animateTo(point);	
		}
	}
	private void draw_only_path(){
		for(int i = 1; i<gp.size(); i++ ){
		GeoPoint point;
      	point = gp.get(i);	
		Data.pat_length += get_destence(gp.get(i-1), gp.get(i))/1000;
        r = new RouteOverlay(gp.get(i-1), gp.get(i), Color.RED);
        OverlayList.add(r); 	
        map_controller.animateTo(point);
		}
	}
	
	private void set_location(){
		gp = new ArrayList<GeoPoint>();
		GeoPoint point1 = new GeoPoint((int)(6.91487420296234 * 1E6), (int)(79.9732575683826 * 1E6));
		GeoPoint point2 = new GeoPoint((int)(6.91429666666667 * 1E6), (int)(79.972255 * 1E6));
		GeoPoint point3 = new GeoPoint((int)(6.91283 * 1E6), (int)(79.9722583333333 * 1E6));	
		GeoPoint point4 = new GeoPoint((int)(6.91308046809007 * 1E6), (int)(79.9658809458963 * 1E6));	
		
		gp.add(point1); 
		gp.add(point2);      
		gp.add(point3); 	
		gp.add(point4); 	
		set_elephants_location(gp);		
	}
	
	private void set_elephants_location(List<GeoPoint> gp){		
	//	 if((OverlayList == null)){			
				GeoPoint point = null;				
				for(int i = 0; i<gp.size(); i++ ){ 
				point = gp.get(i);		
				OverlayList = mapView.getOverlays(); 						
				set_enableCompass();
				Drawable drawable = this.getResources().getDrawable(R.drawable.location);		
				selfitemizedoverlay = new SelfItemizedOverlay(drawable); 	 	
		        OverlayItem overlayitem = new OverlayItem(point, "Name : " + "Test","Locaton : " + point + "\n" + "");	        	         
		        selfitemizedoverlay.addOverlay(overlayitem);
		        OverlayList.add(selfitemizedoverlay);		        		        
		        map_controller.animateTo(point);	
		     //   mapView.invalidate();
		    //    MapController mapController = mapView.getController();        	         
			//   mapController.animateTo(point);
			//   mapController.setZoom(16);	  
		        
				} 
	//		 }
			// else{
			//	 Toast.makeText( getApplicationContext(),"Show My Location",Toast.LENGTH_SHORT).show();
			// }
				 
			 
	}	
	
	private void set_elephant_location_for_animate(GeoPoint point){			
		OverlayList = mapView.getOverlays(); 						
		set_enableCompass();
		Drawable drawable = this.getResources().getDrawable(R.drawable.location);		
		selfitemizedoverlay = new SelfItemizedOverlay(drawable); 	 	
        OverlayItem overlayitem = new OverlayItem(point, "Name : " + "Test","Locaton : " + point + "\n" + "");	        	         
        selfitemizedoverlay.addOverlay(overlayitem);
        OverlayList.add(selfitemizedoverlay);		        		        
        map_controller.animateTo(point);	
	
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {		
		MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu_showselfmap, menu);
	    return true;
	}
	
	

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {	
		if(item.getItemId() == R.id.show_path){		
			if(showpathState == false){
				Data.pat_length = 0.0;
				OverlayList.clear();						
				mapView.invalidate();
				set_elephants_location(gp);	
				draw_path();
				showpathState = true; 				
				destence_of_path.setText("Path: "+String.valueOf(Data.pat_length)+ " km ");
			}
			else if(showpathState == true)
			{			
				OverlayList.clear();						
				mapView.invalidate();
				set_elephants_location(gp);	
				showpathState = false;
				destence_of_path.setText("Path: 0.0 km ");
				
			} 
		}
		if(item.getItemId() == R.id.show_path_animation){	
				OverlayList.clear();						
				mapView.invalidate();			
				kill_run = false;
				runnable = new CountDownRunner();						
				myThread= new Thread(runnable);   
				myThread.start();	
		}
		if(item.getItemId() == R.id.show_only_path){	
			if(only_path_state == false){
				Data.pat_length = 0.0;
				only_path_state = true;
				OverlayList.clear();						
				mapView.invalidate();
				draw_only_path();
				destence_of_path.setText("Path: "+String.valueOf(Data.pat_length)+ " km ");
			}
			else{
				only_path_state = false; 
				OverlayList.clear();						
				mapView.invalidate();
				destence_of_path.setText("Path: 0.0 km "); 
				
			}
		}
		
		return true;
	}
	
	
	 public void doWork(){
	        runOnUiThread(new Runnable() {
	            public void run() {
	                try{	               
	                	if(gp_size<=gp.size()){
	                		set_elephant_location_for_animate(gp.get(gp_size-1));
	                	//	draw_only_path();            		
	                		gp_size++;
	                	}
	                	else{	  
	                		gp_size = 1;  
	                		kill_run = true;	                		
	                	}
	                   
	                }catch (Exception e) {}
	            }
	        });
	    }
	
	 class CountDownRunner implements Runnable{
	        // @Override
	        public void run() {
	              //  while(!Thread.currentThread().isInterrupted()){
	        	while(!kill_run){
	                    try {
	                    	doWork();
	                        Thread.sleep(2000);
	                    } catch (InterruptedException e) {
	                            Thread.currentThread().interrupt();
	                    }catch(Exception e){
	                    } 
	                }
	        }
	    }

	private void set_enableCompass(){
		   myLocationOverlay = new MyLocationOverlay(this,mapView);	
		   myLocationOverlay.enableCompass(); 	
		   OverlayList = mapView.getOverlays();  
		   OverlayList.add(myLocationOverlay);  	
			    
	}
	
	
	public class SelfItemizedOverlay extends com.google.android.maps.ItemizedOverlay<OverlayItem> {	
		
		private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();		    
	   
		
		public SelfItemizedOverlay(Drawable defaultMarker) {		
			super(boundCenterBottom(defaultMarker));
			
		}

		@Override
		protected OverlayItem createItem(int i) {			
			return mapOverlays.get(i);
		}

		@Override
		public int size() {			
			 return mapOverlays.size();
		}
		
		public void addOverlay(OverlayItem overlay) {
			mapOverlays.add(overlay);
			this.populate();
			
		}	
		
	}
	
	
	
	
	public class RouteOverlay extends Overlay {
		
	 	private GeoPoint gp1;
	    private GeoPoint gp2;
	    private int color;
	 
	    public RouteOverlay(GeoPoint gp1, GeoPoint gp2, int color) {
	        this.gp1 = gp1;
	        this.gp2 = gp2;
	        this.color = color;
	    }

		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow,long when) {			
			 	Projection projection = mapView.getProjection();
			//method 1.
			 /*	Paint paint = new Paint();
			    Point point = new Point();
			    projection.toPixels(gp1, point);
			    paint.setColor(color);
			    Point point2 = new Point();
			    projection.toPixels(gp2, point2);
			    paint.setStrokeWidth(2);
			    paint.setAlpha(120);
			    canvas.drawLine(point.x, point.y, point2.x, point2.y, paint);	*/
			 	
			 	
			 	// method 2.			
			 	Point startingPoint = projection.toPixels(gp1, null);
			    Point endingPoint = projection.toPixels(gp2, null);			    
			    Path path = new Path();
			    path.moveTo(startingPoint.x, startingPoint.y);
			    path.lineTo(endingPoint.x, endingPoint.y);			    
			    Paint paint = new Paint();			    
			    paint.setStyle(Paint.Style.STROKE);
			    paint.setColor(color);
			    paint.setStrokeWidth(2);
			    paint.setAlpha(120);
			 //   canvas.drawTextOnPath(length, path, 1, 1, paint);
			    canvas.drawPath(path, paint);			    
			 
			    return super.draw(canvas, mapView, shadow, when);
			    
		}
		

}
	private double get_destence(GeoPoint gp1,GeoPoint gp2) {
		double x1 = gp1.getLatitudeE6()/1E6;
		double y1 = gp1.getLongitudeE6()/1E6;		
		double x2 = gp2.getLatitudeE6()/1E6;
		double y2 = gp2.getLongitudeE6()/1E6;
			
			double earthRadius = 3958.75;
		    double dLat = Math.toRadians(x1-x2);
		    double dLng = Math.toRadians(y1-y2);
		    double a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(Math.toRadians(x1)) * Math.cos(Math.toRadians(x2)) * Math.sin(dLng/2) * Math.sin(dLng/2);
		    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
		    double dist = earthRadius * c;
		    int meterConversion = 1609;
		    return new Float(dist * meterConversion).floatValue();
		}

}
